package com.jstyle.beatecg.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.base.BaseActivity;
import com.jstyle.beatecg.ble.BleManager;
import com.jstyle.beatecg.ble.BleService;
import com.jstyle.beatecg.fragment.DeviceFragment;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.util.GlobalConast;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.ScreenUtils;
import com.jstyle.beatecg.util.SharePreferenceUtils;
import com.jstyle.beatecg.view.MyAlertDialog;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 绑定设备
 */
public class BindDeviceActivity extends BaseActivity implements DeviceFragment.OnFragmentInteractionListener {

    private static final String TAG = "BindViewDeviceActivity";
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.bt_back)
    ImageView btBack;
    @BindView(R.id.bt_bind_device_finish)
    Button btBindViewDeviceFinish;
    @BindView(R.id.bind_device)
    ImageView BindViewDevice;
    boolean isFirst;

    private BluetoothAdapter mBluetoothAdapter;
    private static final int REQUEST_ENABLE_BT = 974;
    private Disposable subscription;
    private String deviceAddress;
    MyAlertDialog alertDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_device);
        ButterKnife.bind(this);
        ScreenUtils.setStatusBarColor(llTitle,getResources().getColor(R.color.colorPrimarytwo));
        initData();
        checkPermissionRequest();
        alertDialog=new MyAlertDialog(this);
    }
    @SuppressLint("CheckResult")
    public void checkPermissionRequest() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.VIBRATE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO
        )
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            Log.e("wyl", permission.name + " is granted.");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时。还会提示请求权限的对话框
                            Log.e("wyl",permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，而且选中『不再询问』
                            Log.e("wyl", permission.name + " is denied.");
                        }
                    }
                });
    }
    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }

    private void initData() {
        subscription = RxBus.getInstance().toObservable(BleData.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData bleData) throws Exception {
                String action = bleData.getAction();
                if (BleService.ACTION_GATT_onDescriptorWrite.equals(action)) {
                    showToast(getString(R.string.connected_success));
                    showBindStatus();
                    disMissProgressDialog();
                   if (isFirst) {
                        startActivity(MainActivity.class);
                    }
                    finish();
                } else if (BleService.diss.equals(action)) {
                    if(alertDialog.isShowing()){
                        alertDialog.dismiss();
                    }
                } else if (BleService.ACTION_GATT_CONNECTED.equals(action)) {
                    disMissProgressDialog();
                } /*else if (BleService.peidui.equals(action)) {
                    if(!alertDialog.isShowing()){
                        alertDialog.show();
                    }
                }*/


                else if (BleService.ACTION_GATT_DISCONNECTED.equals(action)) {
                    showToast(getString(R.string.disonnected));
                    disMissProgressDialog();
                }
            }

        });
       // deviceAddress=SharePreferenceUtils.getSpString(this,SharePreferenceUtils.KEY_ADDRESS);
        showBindStatus();
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        isFirst = getIntent().getBooleanExtra(GlobalConast.KEY_isFirst, false);
    }

    private void showBindStatus() {

        if(null!=SharePreferenceUtils.getUser(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS)){
            deviceAddress= SharePreferenceUtils.getUser(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS).getDeviceAddress();
        }
        int id= TextUtils.isEmpty(deviceAddress)?R.drawable.bind_device:R.drawable.bind_device_unbind;
        BindViewDevice.setImageResource(id);
    }

    @OnClick({R.id.bt_back, R.id.bt_bind_device_finish, R.id.bind_device})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_bind_device_finish:
                if (isFirst) {
                    startActivity(MainActivity.class);
                }
                finish();
                break;
            case R.id.bind_device:
                if (!mBluetoothAdapter.isEnabled()) {
                    enableBluetooth();
                } else {
                    if(TextUtils.isEmpty(deviceAddress)){
                        showDeviceDialog();
                    }else{
                        disconnectOldDevice();
                    }

                }
                break;
        }
    }

    private void disconnectOldDevice() {
        AlertDialog dialog=new AlertDialog.Builder(this).setMessage(getString(R.string.whether_ubind)).setNegativeButton(getString(R.string.cancel),null).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MyBluetoothDevice aa=new MyBluetoothDevice();
                aa.setDeviceAddress(null);
                aa.setIsbind(false);
                SharePreferenceUtils.saveMyBluetoothDevice(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS,aa);
                showBindStatus();
                BleManager.getInstance().disconnectDevice();
            }
        }).create();
        dialog.show();

    }

    DeviceFragment fragment;

    private void showDeviceDialog() {
        DeviceFragment fragment = new DeviceFragment();
        fragment.show(getSupportFragmentManager(), "device");
    }

    private void enableBluetooth() {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    @Override
    public void onFragmentInteraction(final MyBluetoothDevice myBluetoothDevice) {
      //  Log.i(TAG, "onFragmentInteraction: " + myBluetoothDevice.getDeviceAddress());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                BleManager.getInstance().connectDevice(myBluetoothDevice.getDeviceAddress());
            }
        });
        SharePreferenceUtils.saveMyBluetoothDevice(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS,myBluetoothDevice);
        showProgressDialog(getString(R.string.connectting));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
    }
}
